// src/ai/ai.service.ts
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import * as https from 'https';
import { User } from '../../user/entity/user.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';

@Injectable()
export class AiService {
  private readonly apiKey: string;
  private readonly apiUrl: string;

  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {
    this.apiKey = 'sk-5917b78c998149d79703b5be13401799';
    this.apiUrl = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
  }

  async polishMessage(
    originalMessage: string,
    sender: User,
    receiver: User,
    chatType: 'friend' | 'group' = 'friend',
  ): Promise<{
    polishedMessage: string;
    reasoning: string;
    confidence: number;
  }> {
    const prompt = this.buildPrompt(
      originalMessage,
      sender,
      receiver,
      chatType,
    );

    try {
      const result = await this.makeApiRequest(prompt);
      return this.parseAiResponse(result);
    } catch (error) {
      throw new HttpException(
        'AI服务暂时不可用',
        HttpStatus.SERVICE_UNAVAILABLE,
      );
    }
  }

  private buildPrompt(
    originalMessage: string,
    sender: User,
    receiver: User,
    chatType: 'friend' | 'group' = 'friend',
  ): string {
    return `请基于以下信息对情侣间的消息进行润色：

发送方信息：
- MBTI人格：${sender.mbti || '未知'}
- 性别：${sender.sex || '未知'}
- 年龄：${sender.birthday ? this.calculateAge(sender.birthday) : '未知'}

接收方信息：
- MBTI人格：${receiver.mbti || '未知'}
- 性别：${receiver.sex || '未知'}
- 年龄：${receiver.birthday ? this.calculateAge(receiver.birthday) : '未知'}

双方关系：情侣
聊天类型：${chatType === 'friend' ? '私聊' : '群聊'}

原始消息："${originalMessage}"

润色要求：
1. 作为情侣对话，要体现亲密感和爱意
2. 充分考虑接收方的MBTI人格特点和性别特征，使消息更易被接受
3. 保持发送方MBTI人格的性格特点，同时增加情侣间的温暖感
4. 根据聊天类型调整语气（私聊可以更亲密，群聊要适度）
5. 不要改变原意，只在表达方式上优化，增加情侣间的甜蜜感

请返回JSON格式：
{
  "polishedMessage": "润色后的消息",
  "reasoning": "润色理由和考虑因素，特别说明情侣关系的处理",
  "confidence": 0.95
}`;
  }

  private makeApiRequest(prompt: string): Promise<string> {
    return new Promise((resolve, reject) => {
      const requestData = JSON.stringify({
        model: 'qwen3-max',
        messages: [{ role: 'user', content: prompt }],
        temperature: 0.7,
        max_tokens: 1000,
      });

      const url = new URL(this.apiUrl);
      const options = {
        hostname: url.hostname,
        path: url.pathname,
        method: 'POST',
        headers: {
          Authorization: `Bearer ${this.apiKey}`,
          'Content-Type': 'application/json',
          'Content-Length': Buffer.byteLength(requestData),
        },
        timeout: 10000,
      };

      const req = https.request(options, res => {
        let data = '';

        res.on('data', chunk => {
          data += chunk;
        });

        res.on('end', () => {
          if (res.statusCode === 200) {
            resolve(data);
          } else {
            reject(new Error(`API请求失败: ${res.statusCode} ${data}`));
          }
        });
      });

      req.on('error', error => {
        console.log('报错', error);
        reject(error);
      });

      req.on('timeout', () => {
        req.destroy();
        reject(new Error('请求超时'));
      });

      req.write(requestData);
      req.end();
    });
  }

  private parseAiResponse(
    aiResponse: string,
  ): { polishedMessage: string; reasoning: string; confidence: number } {
    try {
      const response = JSON.parse(aiResponse);
      const content = response.choices[0]?.message?.content;

      if (!content) {
        throw new Error('AI响应格式错误');
      }

      // 尝试从内容中提取JSON
      const jsonMatch = content.match(/\{[\s\S]*\}/);
      if (jsonMatch) {
        const parsed = JSON.parse(jsonMatch[0]);
        return {
          polishedMessage: parsed.polishedMessage,
          reasoning: parsed.reasoning,
          confidence: parsed.confidence || 0.8,
        };
      }

      // 如果AI没有返回JSON，返回原始内容
      return {
        polishedMessage: content,
        reasoning: 'AI直接返回了润色结果',
        confidence: 0.7,
      };
    } catch (error) {
      // 解析失败，返回一个默认响应
      return {
        polishedMessage: aiResponse, // 返回原始响应作为消息
        reasoning: '解析AI响应时出错，返回原始消息',
        confidence: 0.6,
      };
    }
  }

  private calculateAge(birthday: string): number {
    if (!birthday) return 0;

    try {
      const birthDate = new Date(birthday);
      const today = new Date();
      let age = today.getFullYear() - birthDate.getFullYear();
      const monthDiff = today.getMonth() - birthDate.getMonth();

      if (
        monthDiff < 0 ||
        (monthDiff === 0 && today.getDate() < birthDate.getDate())
      ) {
        age--;
      }
      return age;
    } catch (error) {
      return 0;
    }
  }
}
